const API_BASE = '/api';
let expenses = [];
let editingExpenseId = null;

// 检查登录状态
function checkAuth() {
    const token = localStorage.getItem('token');
    const user = JSON.parse(localStorage.getItem('user') || '{}');
    
    if (!token) {
        window.location.href = '/admin/';
        return false;
    }
    
    document.getElementById('username').textContent = user.username || 'Admin';
    return true;
}

// API请求封装
async function apiRequest(url, options = {}) {
    const token = localStorage.getItem('token');
    const defaultOptions = {
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        }
    };
    
    const response = await fetch(`${API_BASE}${url}`, {
        ...defaultOptions,
        ...options,
        headers: {
            ...defaultOptions.headers,
            ...options.headers
        }
    });
    
    if (response.status === 401) {
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        window.location.href = '/admin/';
        return;
    }
    
    return response.json();
}

// 加载费用数据
async function loadExpenses() {
    try {
        const data = await apiRequest('/expenses');
        if (data.success) {
            expenses = data.data;
            renderExpenseTable();
            updateStats();
        }
    } catch (error) {
        console.error('加载费用数据失败:', error);
        alert('加载数据失败，请刷新页面重试');
    }
}

// 渲染费用表格
function renderExpenseTable() {
    const tbody = document.getElementById('expenseTableBody');
    tbody.innerHTML = '';
    
    expenses.forEach(expense => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${expense.category}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${expense.name}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">¥${parseFloat(expense.cost).toFixed(2)}</td>
            <td class="px-6 py-4 whitespace-nowrap">
                <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full ${getTripBadgeClass(expense.trip)}">
                    ${expense.trip}
                </span>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <button onclick="editExpense(${expense.id})" class="text-blue-600 hover:text-blue-900 mr-3">编辑</button>
                <button onclick="deleteExpense(${expense.id})" class="text-red-600 hover:text-red-900">删除</button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 获取徒步标签样式
function getTripBadgeClass(trip) {
    const classes = {
        '通用': 'bg-gray-100 text-gray-800',
        'J3': 'bg-blue-100 text-blue-800',
        'J4': 'bg-green-100 text-green-800'
    };
    return classes[trip] || 'bg-gray-100 text-gray-800';
}

// 更新统计数据
function updateStats() {
    const total = expenses.reduce((sum, expense) => sum + parseFloat(expense.cost), 0);
    const categories = new Set(expenses.map(expense => expense.category));
    
    document.getElementById('totalAmount').textContent = `¥${total.toFixed(2)}`;
    document.getElementById('totalItems').textContent = expenses.length;
    document.getElementById('totalCategories').textContent = categories.size;
}

// 显示模态框
function showModal(title = '添加费用') {
    document.getElementById('modalTitle').textContent = title;
    document.getElementById('expenseModal').classList.add('show');
}

// 隐藏模态框
function hideModal() {
    document.getElementById('expenseModal').classList.remove('show');
    document.getElementById('expenseForm').reset();
    document.getElementById('expenseId').value = '';
    editingExpenseId = null;
}

// 编辑费用
function editExpense(id) {
    const expense = expenses.find(e => e.id === id);
    if (!expense) return;
    
    editingExpenseId = id;
    document.getElementById('expenseId').value = id;
    document.getElementById('category').value = expense.category;
    document.getElementById('name').value = expense.name;
    document.getElementById('cost').value = expense.cost;
    document.getElementById('trip').value = expense.trip;
    
    showModal('编辑费用');
}

// 删除费用
async function deleteExpense(id) {
    if (!confirm('确定要删除这条费用记录吗？')) return;
    
    try {
        const data = await apiRequest(`/expenses/${id}`, {
            method: 'DELETE'
        });
        
        if (data.success) {
            alert('删除成功');
            loadExpenses();
        } else {
            alert(data.message || '删除失败');
        }
    } catch (error) {
        console.error('删除费用失败:', error);
        alert('删除失败，请重试');
    }
}

// 保存费用
async function saveExpense(formData) {
    const url = editingExpenseId ? `/expenses/${editingExpenseId}` : '/expenses';
    const method = editingExpenseId ? 'PUT' : 'POST';
    
    try {
        const data = await apiRequest(url, {
            method,
            body: JSON.stringify(formData)
        });
        
        if (data.success) {
            alert(editingExpenseId ? '更新成功' : '添加成功');
            hideModal();
            loadExpenses();
        } else {
            alert(data.message || '保存失败');
        }
    } catch (error) {
        console.error('保存费用失败:', error);
        alert('保存失败，请重试');
    }
}

// 退出登录
function logout() {
    if (confirm('确定要退出登录吗？')) {
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        window.location.href = '/admin/';
    }
}

// 事件监听器
document.addEventListener('DOMContentLoaded', function() {
    if (!checkAuth()) return;
    
    loadExpenses();
    
    // 添加费用按钮
    document.getElementById('addExpenseBtn').addEventListener('click', () => {
        showModal('添加费用');
    });
    
    // 取消按钮
    document.getElementById('cancelBtn').addEventListener('click', hideModal);
    
    // 退出登录按钮
    document.getElementById('logoutBtn').addEventListener('click', logout);
    
    // 费用表单提交
    document.getElementById('expenseForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const formData = {
            category: document.getElementById('category').value,
            name: document.getElementById('name').value,
            cost: parseFloat(document.getElementById('cost').value),
            trip: document.getElementById('trip').value
        };
        
        await saveExpense(formData);
    });
    
    // 点击模态框外部关闭
    document.getElementById('expenseModal').addEventListener('click', (e) => {
        if (e.target === e.currentTarget) {
            hideModal();
        }
    });
});